#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Python依赖安装脚本
用于确保sofaData-process插件所需的Python包已正确安装
"""

import subprocess
import sys
import os
import json
from pathlib import Path

# 设置输出编码为UTF-8，避免Windows下的编码问题
if sys.platform == 'win32':
    import io
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
    sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')

def check_and_install_package(package_name, version=None):
    """
    检查并安装Python包
    
    Args:
        package_name (str): 包名
        version (str, optional): 版本号
    
    Returns:
        bool: 安装是否成功
    """
    # 包名映射：pip安装名 -> Python导入名
    package_import_map = {
        'python-docx': 'docx',
        'openpyxl': 'openpyxl'
    }
    
    # 获取实际的导入名
    import_name = package_import_map.get(package_name, package_name.replace('-', '_'))
    
    try:
        # 尝试导入包
        __import__(import_name)
        print(f"[OK] {package_name} 已安装")
        return True
    except ImportError:
        print(f"[INSTALL] {package_name} 未安装，正在安装...")
        
        try:
            # 构建安装命令
            install_cmd = [sys.executable, '-m', 'pip', 'install']
            if version:
                install_cmd.append(f"{package_name}=={version}")
            else:
                install_cmd.append(package_name)
            
            # 执行安装
            result = subprocess.run(install_cmd, 
                                  capture_output=True, 
                                  text=True, 
                                  check=True)
            
            print(f"[SUCCESS] {package_name} 安装成功")
            return True
            
        except subprocess.CalledProcessError as e:
            print(f"[ERROR] {package_name} 安装失败: {e.stderr}")
            return False
        except Exception as e:
            print(f"[ERROR] {package_name} 安装过程中出现错误: {str(e)}")
            return False

def install_from_requirements():
    """
    从requirements.txt文件安装依赖
    
    Returns:
        bool: 所有依赖是否安装成功
    """
    script_dir = Path(__file__).parent
    requirements_file = script_dir / 'requirements.txt'
    
    if not requirements_file.exists():
        print(f"[ERROR] requirements.txt 文件不存在: {requirements_file}")
        return False
    
    print(f"正在从 {requirements_file} 安装依赖...")
    
    success = True
    
    try:
        with open(requirements_file, 'r', encoding='utf-8') as f:
            lines = f.readlines()
        
        for line in lines:
            line = line.strip()
            if line and not line.startswith('#'):
                if '==' in line:
                    package_name, version = line.split('==', 1)
                    if not check_and_install_package(package_name, version):
                        success = False
                else:
                    if not check_and_install_package(line):
                        success = False
    
    except Exception as e:
        print(f"[ERROR] 读取requirements.txt失败: {str(e)}")
        return False
    
    return success

def main():
    """
    主函数
    """
    print("=== Python依赖检查和安装 ===")
    print(f"Python版本: {sys.version}")
    print(f"Python路径: {sys.executable}")
    print()
    
    # 从requirements.txt安装依赖
    success = install_from_requirements()
    
    if success:
        result = {
            "success": True,
            "message": "所有依赖安装成功"
        }
        print("\n[SUCCESS] 所有依赖安装成功")
    else:
        result = {
            "success": False,
            "error": "部分依赖安装失败"
        }
        print("\n[ERROR] 部分依赖安装失败")
    
    # 输出JSON结果供主程序解析
    print(json.dumps(result, ensure_ascii=False))
    return 0 if success else 1

if __name__ == "__main__":
    sys.exit(main())